package com.example.im.control.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.example.im.R;
import com.example.im.control.activity.AddContactActivity;
import com.example.im.control.activity.GroupListActivity;
import com.example.im.control.activity.InviteActivity;
import com.example.im.control.activity.chatActivity;
import com.example.im.model.Model;
import com.example.im.model.bean.UserInfo;
import com.example.im.utils.Constant;
import com.example.im.utils.SpUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseContactListFragment;
import com.hyphenate.exceptions.HyphenateException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ContactListFragment extends EaseContactListFragment {

    private ImageView iv_contact_red;
    private LocalBroadcastManager mLBM;
    private LinearLayout ll_contact_invite;
    private String mMHxid;
    private BroadcastReceiver ContactInviteChangeReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //更新红点显示
            iv_contact_red.setVisibility(View.VISIBLE);
            SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE,true);
        }
    };
    private BroadcastReceiver ContactChangeReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //刷新页面
            refreshContact();
        }
    };
    private BroadcastReceiver GroupChangeReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //显示红点
            iv_contact_red.setVisibility(View.VISIBLE);
            SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE,true);
        }
    };


    @Override
    protected void initView() {
        super.initView();
        //布局显示加号
        titleBar.setRightImageResource(R.drawable.em_add);

        //添加头布局
        View headerView = View.inflate(getActivity(), R.layout.header_fragment_contact, null);
        listView.addHeaderView(headerView);

        //获取红点对象
        iv_contact_red = (ImageView) headerView.findViewById(R.id.iv_contact_red);

        //获取邀请信息条目的对象
        ll_contact_invite = (LinearLayout)headerView.findViewById(R.id.ll_contact_invite);

        //设置listView条目的点击事件
        setContactListItemClickListener(new EaseContactListItemClickListener() {
            @Override
            public void onListItemClicked(EaseUser user) {
                Intent intent = new Intent(getActivity(), chatActivity.class);

                if (user==null){
                    return;
                }
                //传递参数(给charActivity环信id)
                intent.putExtra(EaseConstant.EXTRA_USER_ID,user.getUsername());
                startActivity(intent);
            }
        });

        //跳转到群组列表页面
        LinearLayout ll_contact_group = (LinearLayout) headerView.findViewById(R.id.ll_contact_group);
        ll_contact_group.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(), GroupListActivity.class);

                startActivity(intent);
            }
        });

    }


    @Override
    protected void setUpView() {
        super.setUpView();
        //初始化红点显示
        //在之前存储的SharedPreferences中取出
        boolean isNewInvite = SpUtils.getInstance().getBoolean(SpUtils.IS_NEW_INVITE, false);//默认不显示
        iv_contact_red.setVisibility(isNewInvite?View.VISIBLE:View.GONE);
        //注册广播
        mLBM = LocalBroadcastManager.getInstance(getActivity());
        mLBM.registerReceiver(ContactInviteChangeReceiver,new IntentFilter(Constant.CONTACT_INVITE_CHANGED));
        mLBM.registerReceiver(ContactChangeReceiver,new IntentFilter(Constant.CONTACT_CHANGED));
        mLBM.registerReceiver(GroupChangeReceiver,new IntentFilter(Constant.GROUP_INVITE_CHANGED));

        //从环信服务器获取所有的联系人信息
         getContactFromHxServer();

        //绑定listView和contextmenu
        registerForContextMenu(listView);



        titleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AddContactActivity.class);
                startActivity(intent);
            }
        });


        //邀请信息条目的点击事件
        ll_contact_invite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //红点处理
                iv_contact_red.setVisibility(View.GONE);
                SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE,false);

                //跳转到邀请信息列表
                Intent intent=new Intent(getActivity(), InviteActivity.class);
                startActivity(intent);
            }
        });


    }

    @Override
    public void onCreateContextMenu(@NonNull  ContextMenu menu, @NonNull View v, @Nullable ContextMenu.ContextMenuInfo menuInfo) {

        //获取环信id
        int position = ((AdapterView.AdapterContextMenuInfo) menuInfo).position;

        EaseUser easeUser = (EaseUser) listView.getItemAtPosition(position);

        mMHxid = easeUser.getUsername();
        //添加布局
        getActivity().getMenuInflater().inflate(R.menu.delete,menu);



    }

    @Override
    public boolean onContextItemSelected(@NonNull  MenuItem item) {
       if(item.getItemId()==R.id.contact_delete){

           //执行删除选中的联系人操作
           deleteContact();
           return true;
       }


        return super.onContextItemSelected(item);
    }

    private void deleteContact() {
        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                //从环信服务器中删除联系人
                try {
                    EMClient.getInstance().contactManager().deleteContact(mMHxid);
                    //本地数据库的更新
                    Model.getInstance().getDbManager().getContactTableDao().deleteContactByHxId(mMHxid);


                    if (getActivity()==null){
                        return;
                    }

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //toast提示
                            Toast.makeText(getActivity(),"删除"+mMHxid+"成功",Toast.LENGTH_SHORT).show();

                            //刷新页面
                            refreshContact();
                        }
                    });
                } catch (HyphenateException e) {
                    e.printStackTrace();

                    if (getActivity()==null){
                        return;
                    }
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(),"删除"+mMHxid+"失败",Toast.LENGTH_SHORT).show();
                        }
                    });
                }




            }
        });
    }

    //从环信服务器获取所有的联系人信息
    private void getContactFromHxServer() {
        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
            @Override
            public void run() {

                try {
                    //获取到所有好友的环信id(当用户点击接受后，这里获得的数据就会变化)
                    List<String> hxids= EMClient.getInstance().contactManager().getAllContactsFromServer();
                    //校验
                    if(hxids!=null&&hxids.size()>=0){
                     List<UserInfo> contacts=new ArrayList<UserInfo>();
                     //转换
                        for(String hxid:hxids){
                            UserInfo userInfo = new UserInfo(hxid);
                            contacts.add(userInfo);
                        }

                        //保存好友信息到本地数据库
                        Model.getInstance().getDbManager().getContactTableDao().saveContacts(contacts,true);
                        //当我们快速切换Fragment时，可能切换到另一个Fragment时，此时的Fragment已经结束了获取不到getActivity，
                        // 因为此时的Fragment生命周期执行到onDestory销毁了，而线程会在后台继续执行所以为了确保
                        //不报一个空指针，所以判断一下
                        if(getActivity()==null){
                            return;
                        }
                        //刷新页面
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //刷新页面的方法
                                refreshContact();
                            }
                        });

                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private void refreshContact() {
        //获取数据
        List<UserInfo> contacts = Model.getInstance().getDbManager().getContactTableDao().getContacts();
        //校验
        if(contacts!=null&&contacts.size()>=0){
            //设置数据
            Map<String, EaseUser> contactsMap=new HashMap<>();
            //转换
            for(UserInfo contact:contacts){
                EaseUser easeUser = new EaseUser(contact.getHxid());
                contactsMap.put(contact.getHxid(),easeUser);
            }
            //设置数据（因为继承的是环信的ease，所以刷新前需要设置数据）
            setContactsMap(contactsMap);

            //刷新页面
            refresh();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //关闭广播
        mLBM.unregisterReceiver(ContactInviteChangeReceiver);
        mLBM.unregisterReceiver(ContactChangeReceiver);
        mLBM.unregisterReceiver(GroupChangeReceiver);
    }
}
